package top.kaoshanji.p3ch13a;

import java.io.FilePermission;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/2/8 09:19
 */
public class WriteFile {

    // 代码清单-p3ch13a-419页a：使用 SecurityManager 类进行权限检查
    public void writeFile2(Path path, byte[] content) throws IOException {
        SecurityManager securityManager = System.getSecurityManager();
        if (null != securityManager) {
            securityManager.checkWrite(path.toString());
        }

        Files.write(path, content);
    }

    // 代码清单-p3ch13a-419页b：使用 AccessController 类进行权限检查
    public void writeFile(Path path, byte[] content) throws IOException {
        FilePermission permission = new FilePermission(path.toString(), "write");
        AccessController.checkPermission(permission);

        Files.write(path, content);
    }

    // 代码清单-p3ch13a-421页b：使用特权动作写入文件的示例
    public void writeFileWithPrivilege(final Path path, final byte[] content) {

        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<String>() {
                @Override
                public String run() throws Exception {
                    Files.write(path, content);
                    return path.toString();
                }
            });

        } catch (PrivilegedActionException e) {
            throw new RuntimeException(e);
        }


    }

}
